import time
import webbrowser

import wx
from wx.svg import SVGimage

from config import Version, Config
from utils.path import get_file_path
from serve.func import Proxy, open_log_path, AutoBoot
from window.button import RoundButton
from window.dialog import ExitDialog
from window.sys_tray import TaskBarIcon


class Home(wx.Frame):

    def __init__(self, parent=None, title=None, size=None, icon=None):
        super(Home, self).__init__(parent, title=title, size=size, style=wx.DEFAULT_FRAME_STYLE & ~wx.MAXIMIZE_BOX)
        self.SetIcon(icon)
        self.SetMinSize(size)
        self.SetMaxSize(size)
        self.SetBackgroundColour("#FFFFFF")
        self.Bind(wx.EVT_CLOSE, self.on_close)

        self.init_ui()
        self.init_menu()
        self.init_tray = TaskBarIcon(self)

        self.update_msg = Version().update_msg()
        if len(self.update_msg) != 0:
            wx.CallLater(5000, self.show_update_message)

        self.Centre()
        self.Show()

    def init_ui(self):
        pnl = wx.Panel(self)
        box_sizer = wx.BoxSizer(wx.VERTICAL)
        logo_sizer = wx.BoxSizer(wx.VERTICAL)
        logo_svg_path = get_file_path(r"resources\logo.svg")
        pic = self.load_svg(logo_svg_path)
        self.logo = wx.StaticBitmap(pnl, wx.ID_ANY, pic, wx.DefaultPosition, wx.DefaultSize, 0)
        self.connect_btn = RoundButton(parent=pnl,
                                       size=(150, 40),
                                       label="点 击 连 接",
                                       font_size=13,
                                       name="connect",
                                       bg=(37, 188, 189))
        self.connect_btn.SetBackgroundColour((255, 255, 255))
        self.connect_btn.Bind(wx.EVT_LEFT_DOWN, self._func_connect_btn)
        logo_sizer.Add(self.logo, flag=wx.ALL | wx.ALIGN_CENTER_HORIZONTAL, border=20)
        logo_sizer.Add(self.connect_btn, flag=wx.ALL | wx.ALIGN_CENTER_HORIZONTAL, border=5)

        setting_sizer = wx.BoxSizer(wx.VERTICAL)
        self.ch_boot = wx.StaticText(pnl, wx.ID_ANY, "待开发区域", wx.DefaultPosition,wx.DefaultSize, 0)
        self.st_version = wx.StaticText(pnl, wx.ID_ANY, Version().version_num, wx.DefaultPosition,wx.DefaultSize, 0)
        self.st_version.Wrap(-1)
        setting_sizer.Add(self.ch_boot, 0, wx.ALL, 5)
        setting_sizer.Add((0, 0), 1, wx.EXPAND, 5)
        setting_sizer.Add(self.st_version, 0, wx.ALL | wx.ALIGN_RIGHT, 5)

        box_sizer.Add(logo_sizer, 35, wx.EXPAND, 5)
        box_sizer.Add(setting_sizer, 65, wx.EXPAND, 5)
        pnl.SetSizer(box_sizer)

    def init_menu(self):
        """菜单栏"""
        menu_bar = wx.MenuBar(0)

        setting_menu = wx.Menu()
        self.boot_item = wx.MenuItem(setting_menu, wx.ID_ANY, "开机启动", wx.EmptyString, wx.ITEM_NORMAL)
        switch_path = get_file_path(r"resources\assets\switch_off.svg")
        if AutoBoot().status is True:
            switch_path = get_file_path(r"resources\assets\switch_on.svg")
        self.boot_item.SetBitmap(self.load_svg(switch_path, 16, 16))
        self.Bind(wx.EVT_MENU, self.auto_boot, self.boot_item)
        setting_menu.Append(self.boot_item)

        help_menu = wx.Menu()
        show_log_item = wx.MenuItem(help_menu, wx.ID_ANY, "查看日志", wx.EmptyString, wx.ITEM_NORMAL)
        show_conf_item = wx.MenuItem(help_menu, wx.ID_ANY, "查看配置", wx.EmptyString, wx.ITEM_NORMAL)
        help_menu.Append(show_log_item)
        help_menu.Append(show_conf_item)
        self.Bind(wx.EVT_MENU, self.open_log, show_log_item)
        self.Bind(wx.EVT_MENU, self.show_config_message, show_conf_item)

        menu_bar.Append(setting_menu, "设置")
        menu_bar.Append(help_menu, "帮助")
        self.SetMenuBar(menu_bar)

    def _func_connect_btn(self, event):
        """连接按键的功能实现"""
        status = self.connect_btn.GetName()
        if status == "connect":
            background_color = (221, 58, 95)
            label = "点 击 断 开"
            name = "disconnect"
            config = Config()
            proxy_server = config.local_proxy_server
            exclude_addresses = config.exclude_addresses
            Proxy().set_proxy(proxy_server, exclude_addresses)
        else:
            background_color = (37, 188, 189)
            name = "connect"
            label = "点 击 连 接"
            Proxy().turn_off()

        time.sleep(0.7)
        self.connect_btn.set_label(label)
        self.connect_btn.set_background(background_color)
        self.connect_btn.SetName(name)
        self.connect_btn.Refresh()

    def on_close(self, event):
        """点击关闭按键时弹出自定义对话框"""
        ex_msg = ExitDialog(self)
        ex_msg.ShowModal()
        ex_msg.Destroy()

    def open_log(self, event):
        """打开日志"""
        open_log_path()

    @staticmethod
    def load_svg(path, w=100, h=100):
        img = SVGimage.CreateFromFile(path)
        bmp_size = wx.Size(w, h)
        bmp = img.ConvertToScaledBitmap(bmp_size)
        return bmp

    def show_update_message(self):
        """显示最新的版本的更新信息"""
        title = "新版本{}可用".format(self.update_msg["new_version"])
        msg = "检测有新版本，请打开网页进行下载\n版本信息：\n{}".format(self.update_msg["description"])
        dlg = wx.MessageDialog(self, msg, title, wx.YES_NO | wx.ICON_INFORMATION)
        result = dlg.ShowModal()
        dlg.Destroy()

        if result == wx.ID_YES:
            webbrowser.open(self.update_msg["update_url"])

    def show_config_message(self, event):
        """显示配置信息"""
        title = "配置信息"
        msg = ""
        for key, value in Config().to_dict().items():
            if key in ["inform", "exclude_addresses"]:
                continue
            msg = msg + f"{key}: {value}\n"
        wx.MessageBox(msg, title, wx.OK | wx.ICON_INFORMATION)

    def auto_boot(self, event):
        """开机启动"""
        boot = AutoBoot()
        if boot.status:
            switch_path = get_file_path(r"resources\assets\switch_off.svg")
            self.boot_item.SetBitmap(self.load_svg(switch_path, 16, 16))
            boot.set_boot(False)
        else:
            switch_path = get_file_path(r"resources\assets\switch_on.svg")
            self.boot_item.SetBitmap(self.load_svg(switch_path, 16, 16))
            boot.set_boot(True)
